package com.ruima.study.arithmetic.dynamicplanning;

/**
 * <p>
 * <p>找到连续子序列最大和</p>
 * <p>
 * <p>Copyright (c) 2024/09/21/星期六 13:15, 马锐个人 All Rights Reserve</p>
 *
 * @author marui
 * @version [V1.0]
 */
public class Demo {


    public static void main(String[] args) {
        int[] nums = {3, -4, 2, -1, 2, 6, -5, 4};
        System.out.println("Maximum Subarray Sum: " + maxSubArray(nums));

    }

    public static int maxSubArray(int[] nums) {
        if (nums == null || nums.length == 0) {
            throw new IllegalArgumentException("Array must not be null or empty");
        }

        int maxCurrent = nums[0];
        int maxGlobal = nums[0];

        for (int i = 1; i < nums.length; i++) {
            // 更新当前最大子序列和
            maxCurrent = Math.max(nums[i], maxCurrent + nums[i]);
            // 更新全局最大子序列和
            if (maxCurrent > maxGlobal) {
                maxGlobal = maxCurrent;
            }
        }

        return maxGlobal;
    }


}
